<?php

namespace app\api\controller\wanlshop;

use addons\wanlshop\library\Decrypt\weixin\wxBizDataCrypt;
use addons\wanlshop\library\WanlChat\WanlChat;
use addons\wanlshop\library\WeixinSdk\Security;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\api\controller\wanlshop\Common;

use app\common\model\AddressLocation;
use app\common\model\GradeOrder;
use app\common\model\User as UserModel;
use fast\Arr;
use fast\Random;
use fast\Http;
use think\Db;
use think\Validate;

/**
 *推广
 */
class Promotion extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * 获取分享二维码
     */
    public function getqrcode()
    {
        $Common=new Common();
        $res=$Common->getqrcode();
        return $res;
    }
    
   	/**
	 * 推广海报模版列表
	 */
	public function tgHbMbList()
	{
        $this->request->filter(['strip_tags']);
        $where['status'] = 'normal';
        $list = model('app\admin\model\Poster')
            ->field('id,title,waittext,bg_image,data,qr_type,weigh')
            ->where($where)
            ->order('weigh desc')
            ->select();
        $this->success('返回成功', $list);
	}

   	/**
	 * 我的粉丝
	 */
	public function myfans()
	{
		$start_time = $this->request->post('start_time');
        $end_time = $this->request->post('end_time');
		$where['pid']=$this->auth->id;
		if(!empty($start_time)&&!empty($end_time)){
           $where['createtime']=['between',[strtotime($start_time),strtotime($end_time)]];
		}

		$this->request->filter(['strip_tags']);
		$list = model('app\common\model\User')
		    ->field('id,avatar,mobile,createtime,nickname')
			->where($where)
			->order('updatetime desc')
			->paginate();
		$this->success('返回成功', $list);
	}

   	/**
	 * 我的邀请人
	 */
	public function mypid()
	{
		$where['id']=$this->auth->id;
		$user = model('app\common\model\User')->field('pid,createtime')->where('id',$this->auth->id)->find();

		// 我的邀请人信息
		$this->request->filter(['strip_tags']);
		$pid_info = model('app\common\model\User')
		    ->field('id,avatar,mobile,createtime,nickname')
			->where('id',$user['pid'])
			->find();
		$pid_info['createtime']	=$user['createtime'];

		// 累计订单数
		$whereConsum['user_id']=$this->auth->id;
		$whereConsum['money']=['>',0];
		$whereConsum['createtime']=['between',[strtotime("today"),strtotime("tomorrow") - 1]];
		$order_count= model('app\common\model\ConsumCard')->where($whereConsum)->count();

		// 我的今日粉丝数
		$fansWhere['pid']=$this->auth->id;
		$fansWhere['createtime']=['between',[strtotime("today"),strtotime("tomorrow") - 1]];
		$fans_count = model('app\common\model\UserGrade')->where($fansWhere)->count();		

        $data['order_count']=$order_count;
        $data['fans_count']=$fans_count;
        $data['pid_info']=$pid_info;

		$this->success('返回成功', $data);
	}
   
	/**
	 * 奖励明细
	 */
	public function rewardList()
	{
		$params=$this->request->Post();
		if($params['user_id']){
			$where['order_user_id']=$params['user_id'];
		}

		// 消费券奖励明细
		$where['user_id']=$this->auth->id;
		$where['money']=['>',0];
		$reward_info= model('app\common\model\ConsumCard')
		        ->field('id,order_no,createtime,money')
				->where($where)
				->order('updatetime desc')
				->paginate();

	    // 累计订单数
		$order_count= model('app\common\model\ConsumCard')->where($where)->count();

	    // 累计消费券
		$reward_sum= model('app\common\model\ConsumCard')->where($where)->sum('money');

        $data['order_count']=$order_count;
        $data['reward_sum']=$reward_sum;
        $data['reward_info']=$reward_info;

		$this->success('返回成功', $data);
	}

	/**
	 * 粉丝团
	 */
	public function fansList()
	{
		$user_id=$this->auth->id;
		// $user_id=2;

        // 下三级用户id
		$userid_arr=$this->my_team($user_id);
		
		// 今日新增粉丝团人数
		$dayfansWhere['id']=['in',$userid_arr];
		$dayfansWhere['createtime']=['between',[strtotime("today"),strtotime("tomorrow") - 1]];
		$day_fans_count = model('app\common\model\User')->where($dayfansWhere)->count();	
		
		// 总粉丝团人数
		$totalfansWhere['pid']=$user_id;
		$total_fans_count = count($userid_arr);	

		//今日业绩
		$dayScoreWhere['user_id']=['in',$userid_arr];
		$dayScoreWhere['pay_state']=1;
		$dayScoreWhere['createtime']=['between',[strtotime("today"),strtotime("tomorrow") - 1]];
		$day_score=model('app\api\model\wanlshop\Pay')->where($dayScoreWhere)->sum('order_price');
		
		//本月业绩
		$monthScoreWhere['user_id']=['in',$userid_arr];
		$monthScoreWhere['pay_state']=1;
		$monthScoreWhere['createtime']=['between',[strtotime(date('Y-m-01 00:00:00')),strtotime(date('Y-m-t 23:59:59'))]];
		$month_score=model('app\api\model\wanlshop\Pay')->where($monthScoreWhere)->sum('order_price');

		//今日绑定门店
		$dayBindingWhere['star_reference_time']=['between',[date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59')]];
		$dayBindingWhere['star_reference_userid']=$user_id;
		$day_binding_shop = model('app\api\model\wanlshop\Shop')->where($dayBindingWhere)->count();	

		//总绑定门店
		$total_binding_shop = model('app\api\model\wanlshop\Shop')->where('star_reference_userid',$user_id)->count();	

		// 我的粉丝团
		$fans_list = model('app\common\model\User')->field('id,avatar,nickname,level')->where(['id'=>['in',$userid_arr]])->paginate();
		$level_arr=[1=>'普通会员',2=>'vip会员',3=>'星推官',4=>'区县服务商',5=>'全国运营中心'];
		foreach($fans_list as $k => &$v){
			$v['sort']=$k+1;
			$v['level_text']=$level_arr[$v['level']];
			$v['apply_num']=model('app\common\model\User')->where('pid',$v['id'])->count();
		}

        $data['day_fans_count']=$day_fans_count;// 今日新增粉丝数
        $data['total_fans_count']=$total_fans_count;// 总粉丝团人数
        $data['day_score']=$day_score;//今日业绩
        $data['month_score']=$month_score;//本月业绩
        $data['day_binding_shop']=$day_binding_shop;//今日绑定门店
        $data['total_binding_shop']=$total_binding_shop;//总绑定门店
        $data['fans_list']=$fans_list;//我的粉丝团

		$this->success('返回成功', $data);
	}

    // 获取当前邀请的下级 id 数组
	public function my_team($id)
	{
		$i=0;
		$info = $this->getChild($id,$i);
		$usertguid = [];//获取所有下级
		foreach($info as $k=>$v){
			$usertguid[$k] = $v['id'];
		}

		return $usertguid;
	}
		
	// 获取当前邀请的下级 pid 字段为储存的上级用户的ID编号
	public function getChild($id,$i)
	{
		$i++;
		static $arr=array();  //第一次调用时初始化
		//通过邀请码查询当前邀请码下级用户
		$data=model('app\common\model\User')->field('id')->where('pid',$id)->select();
		//遍历获取信息，调用当前方法直至没有下级用户
		foreach ($data as $key => $value) {
			$arr[] = $value;
			if($i<3){
			  $this->getChild($value['id'],$i);  //返回查询 继续查用户的ID号
		    }
		}

		return $arr;
	}

	/*
	* 推广身份申请-详情
	*/
	public function applyDetails()
	{
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			$data = model('app\common\model\AuthLevel')
			->where(['user_id' => $this->auth->id])
			->find();
			$this->success('返回成功', $data);
		}
		$this->error(__('非法请求'));
	}
	
	/**
	 * 推广身份申请-申请
	 */
	public function apply()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
 
		$data=$this->request->Post();
 
		if(!isset($data['level'])){
			$this->error(__('当前上传类型level必传'));
		}
 
		$find=model('app\common\model\AuthLevel')->where('user_id',$this->auth->id)->value('id');
		$data['verify']=2;
		if($find){
			$res=model('app\common\model\AuthLevel')->where('user_id',$this->auth->id)->update($data);
		}else{
			$data['user_id']=$this->auth->id;
			$res=model('app\common\model\AuthLevel')->save($data);
		}
 
		if($res){
			$this->success('请求成功');
		}else{
			$this->error(__('请求失败'));
		}
	}
}